import 'package:flutter/material.dart';
import 'package:xws/models/notify/chat_obj.dart';
import 'package:xws/state/user_state.dart';
import 'package:xws/utils/dio_utils/request/user_req.dart';
import 'package:xws/utils/push_util.dart';
import 'package:xws/widgets/refresh_widget/refresh_load_view.dart';
import 'package:xws/widgets/safe_scaffold.dart';

import 'notify_item.dart';

/// 通知界面
class NotifyPage extends StatefulWidget {
  const NotifyPage({Key? key}) : super(key: key);

  @override
  State<NotifyPage> createState() => _NotifyPageState();
}

class _NotifyPageState extends State<NotifyPage> {
  late RefreshViewController<ChatObj> _viewController;
  int _totalLen = 0;

  @override
  void initState() {
    super.initState();
    _viewController = RefreshViewController<ChatObj>();
    _init();
  }

  /// 初始化
  Future<void> _init() async {
    PU.notifyPageNow = true;
    PU.putHandler((_) async {
      await _refresh();
      PU.cancelJPushNotify(clearAll: true);
    });

    PU.cancelJPushNotify(clearAll: true);
  }

  /// 刷新消息
  Future<void> _refresh() async {
    us.updateBasicInfo();
    await _viewController.refresh();
  }

  @override
  void dispose() {
    PU.notifyPageNow = false;
    PU.popHandler();
    _viewController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      titleText: '通知消息',
      body: RefreshLoadView<ChatObj>(
        viewController: _viewController,
        itemBuilder: (int i, ChatObj c) {
          bool isFirst = false;
          if ((i == 0 || i == 1) && c.type == RoomType.USER) {
            isFirst = true;
          }

          return NotifyItem(
            isFirst: isFirst,
            isLast: _totalLen == i + 1,
            chatObj: c,
            refresh: _refresh,
          );
        },
        onRefresh: (_, __) async => await getChatList(),
        onLoad: (int page, _) async => await getChatList(pageNum: page),
        onListChange: (List<ChatObj> d) async {
          _totalLen = d.length;
        },
        padding: const EdgeInsets.all(16),
        splitWidget: const SizedBox(height: 2),
      ),
    );
  }
}
